package com.digitalxpert.completer;

import java.text.ParseException;
import java.util.regex.Pattern;
import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatter;

/**
 * Class InnFormatter
 *
 * @author Yerokhin Yuri
 *         copyright by Zsoft Company
 * @version 1.0
 */

public class InnFormatter extends DefaultFormatter {
    private Pattern pattern = Pattern.compile("\\d{0,4}");
    private Pattern mask = Pattern.compile("\\d{0,4}+%");
    private JFormattedTextField tf = null;
    public InnFormatter() {
    }
    public void install(JFormattedTextField ftf) {
        super.install(ftf);
        tf = ftf;
    }
    public Object stringToValue(String string) throws ParseException {
        String value = string.trim();
        if (!pattern.matcher(string).matches()) {
            if (!mask.matcher(string).matches()) {
                value = (String) tf.getValue();
                tf.setValue(value);
            } else {
                if (tf != null)
                    tf.setValue(value);
            }
        } else {
            if (!tf.isFocusOwner()) {
                value = value + '%';
            }
            if (tf != null)
                tf.setValue(value);
        }
        return value;
    }
    public String valueToString(Object value) throws ParseException {
        if (value == null)
            return "";
        return value.toString();
    }
}
